#include "MainServer.h"
#include "manager/DBManager.h"
#include "manager/UDPManager.h"
#include "manager/UserManager.h"

MainServer::MainServer(QObject* parent) : QObject(parent), udpSocket(new QUdpSocket(this)) {
    if (!udpSocket->bind(QHostAddress::Any, port)) {
        qCritical() << "UDP server failed to start:" << udpSocket->errorString();
    } else {
        qDebug() << "UDP server listening on port " << port;
    }

    DbManager::instance()->init("DB.db");

    connect(udpSocket, &QUdpSocket::readyRead, this, &MainServer::onReadyRead);
}

void MainServer::onReadyRead() {
    while (udpSocket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(int(udpSocket->pendingDatagramSize()));

        QHostAddress sender;
        quint16 senderPort;
        udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);

        // 生成消息并交给 TCPManager 处理（命名可保留）
        MSG msg = MessageHelper::makeMessage(datagram);

        UDPManager::instance()->receiveData(datagram, sender, senderPort);  
    }
}
